我新增了一個controller(UploadFileController.cs),裡面內容如下,橘色區塊是我自己加入的,其他是原本生成時就有
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace UploadFileTest.Controllers
{
public class UploadFileController : Controller
{
// GET: UploadFile
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
if (file != null)
{
string fileName = Path.GetFileName(file.FileName);
string path = Path.Combine(Server.MapPath("~/Files/"), fileName);
file.SaveAs(path);
TempData["message"] = "上傳成功";
}
else
{
TempData["message"] = "請先選檔案";
}
return RedirectToAction("Index");
}
}
}
另外再新增了一個View(Index.cshtml),裡面內容如下,橘色區塊也是自己加入,其他部分生成時就有了
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<div>
@using (Html.BeginForm("Index", "UploadFile", FormMethod.Post, new {enctype = "multipart/form-data"}))
{
<input type="file" id="file" name="file"/>
@Html.Raw(TempData["message"])
<br/>
<input type="submit" value="上傳檔案"/>
}
</div>
留言列表